<?php

namespace app\store\controller\wxapp;

use app\store\controller\Controller;
use app\store\model\Category as CategoryModel;
use app\store\model\sharing\Category as SharingCategoryModel;
use app\store\model\article\Category as ArticleCategoryModel;
use app\store\model\WxappPage as WxappPageModel;
use app\store\model\WxappCategory as WxappCategoryModel;

/**
 * 小程序页面管理
 * Class Page
 * @package app\store\controller\wxapp
 */
class Page extends Controller
{
    /**
     * 页面列表
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $model = new WxappPageModel;
        $list = $model->getList();
        return $this->fetch('index', compact('list'));
    }

    /**
     * 新增页面
     * @return array|mixed
     */
    public function add()
    {
        $model = new WxappPageModel;
        $form = db('form')->field('id,name')->where('wxapp_id', $model::$wxapp_id)->select();
        if (!$this->request->isAjax()) {
            return $this->fetch('edit', [
                'defaultData' => json_encode($model->getDefaultItems()),
                'jsonData' => json_encode(['page' => $model->getDefaultPage(), 'items' => []]),
                'list' => $form->toArray(),
                'opts' => json_encode([
                    'catgory' => CategoryModel::getCacheTree(),
                    'sharingCatgory' => SharingCategoryModel::getCacheTree(),
                    'articleCatgory' => ArticleCategoryModel::getALL(),
                ])
            ]);
        }
        // 接收post数据
        $post = $this->request->post('data', null, null);
        if (!$model->add(json_decode($post, true))) {
            return $this->renderError('添加失败');
        }

        // // 判断是否有自定义表单，添加记录 mvp 
        // $post = json_decode($post);
        // $field = '';
        // foreach ($post->items as $v) {
        //     $type = $v->type;
        //     if ($type == 'input' || $type == 'picker') {
        //         $field .= $v->params->tip . '_';
        //     }
        // }
        // $field = rtrim($field, '_');
        
        // $sign = false;
        // foreach ($post->items as $v) {
        //     $type = $v->type;
        //     if ($type == 'input' || $type == 'picker') {
        //         $sign = true;
        //         break;
        //     }
        // }
        
        // if ($sign) {
        //     $data = [];
        //     $data['wxapp_id'] = $model::$wxapp_id;
        //     $data['page_id'] = $model->getLastInsID();
        //     $data['page_name'] = $post->page->params->name;
        //     $data['field'] = $field; 
        //     db('custom_form')->insert($data);
        // }
        return $this->renderSuccess('添加成功', url('wxapp.page/index'));
    }

    /**
     * 编辑页面
     * @param $page_id
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function edit($page_id)
    {
        $model = WxappPageModel::detail($page_id);
        $form = db('form')->field('id,name')->where('wxapp_id', $model::$wxapp_id)->select();
        if (!$this->request->isAjax()) {
            return $this->fetch('edit', [
                'defaultData' => json_encode($model->getDefaultItems()),
                'jsonData' => json_encode($model['page_data']),
                'list' => $form->toArray(),
                'opts' => json_encode([
                    'catgory' => CategoryModel::getCacheTree(),
                    'sharingCatgory' => SharingCategoryModel::getCacheTree(),
                    'articleCatgory' => ArticleCategoryModel::getALL(),
                ])
            ]);
        }
        // 接收post数据
        $post = $this->request->post('data', null, null);
        if (!$model->edit(json_decode($post, true))) {
            return $this->renderError('更新失败');
        }
        
        // // 判断是否有自定义表单，添加记录 mvp
        // $post = json_decode($post);
        // $field = '';
        // foreach ($post->items as $v) {
        //     $type = $v->type;
        //     if ($type == 'input' || $type == 'picker') {
        //         $field .= $v->params->tip . '_';
        //     }
        // }
        // $field = rtrim($field, '_');
        
        // $sign = false;
        // foreach ($post->items as $v) {
        //     $type = $v->type;
        //     if ($type == 'input' || $type == 'picker') {
        //         $sign = true;
        //         break;
        //     }
        // }
        
        // if ($sign) {
        //     $data = [];
        //     $data['wxapp_id'] = $model::$wxapp_id;
        //     $data['page_id'] = $page_id;
        //     $data['page_name'] = $post->page->params->name;

        //     $one = db('custom_form')->where($data)->find();
        //     $data['field'] = $field; 
        //     if ($one) {
        //         $data['id'] = $one['id']; 
        //         db('custom_form')->update($data);
        //     } else {
        //         db('custom_form')->insert($data);
        //     }
        // } else {
        //     $data = [];
        //     $data['wxapp_id'] = $model::$wxapp_id;
        //     $data['page_id'] = $page_id;
        //     db('custom_form')->where($data)->delete();
        // }
        return $this->renderSuccess('更新成功', url('wxapp.page/index'));
    }

    /**
     * 删除页面
     * @param $page_id
     * @return array
     * @throws \think\exception\DbException
     */
    public function delete($page_id)
    {
        // 帮助详情
        $model = WxappPageModel::detail($page_id);
        if (!$model->setDelete()) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        
        // $data = [];
        // $data['wxapp_id'] = $model::$wxapp_id;
        // $data['page_id'] = $page_id;
        // db('custom_form')->where($data)->delete();
        return $this->renderSuccess('删除成功');
    }

    /**
     * 设置默认首页
     * @param $page_id
     * @return array
     * @throws \think\exception\DbException
     */
    public function setHome($page_id)
    {
        // 帮助详情
        $model = WxappPageModel::detail($page_id);
        if (!$model->setHome()) {
            return $this->renderError($model->getError() ?: '设置失败');
        }
        return $this->renderSuccess('设置成功');
    }

    /**
     * 分类模板
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function category()
    {
        $model = WxappCategoryModel::detail();
        if ($this->request->isAjax()) {
            if ($model->edit($this->postData('category'))) {
                return $this->renderSuccess('更新成功');
            }
            return $this->renderError($model->getError() ?: '更新失败');
        }
        return $this->fetch('category', compact('model'));
    }

    /**
     * 页面链接
     * @return mixed
     */
    public function links()
    {
        return $this->fetch('links');
    }
    
    /**
     * 表单列表
     * @return mixed
     */
    public function formList()
    {
        $model = new WxappPageModel;
        $wxapp_id = $model::$wxapp_id;
        $list = db('form')->order('id desc')->where('wxapp_id',$wxapp_id)->select();
        return $this->fetch('formList', [
            'list' => $list
        ]);
    }
    
    /**
     * 添加表单
     * @return mixed
     */
    public function formAdd()
    {
        $model = new WxappPageModel;
        if (!$this->request->isAjax()) {
            return $this->fetch('formAdd', [
                'defaultData' => json_encode($model->getFormItems()),
                'jsonData' => json_encode(['page' => $model->getFormPage(), 'items' => []]),
                'opts' => json_encode([
                    'catgory' => CategoryModel::getCacheTree(),
                    'sharingCatgory' => SharingCategoryModel::getCacheTree(),
                    'articleCatgory' => ArticleCategoryModel::getALL(),
                ])
            ]);
        }

        // 接收post数据
        $post = $this->request->post('data', null, null);
        $post = json_decode($post, true);
        $field = '';
        
        foreach ($post['items'] as $v) {
            $type = $v['type'];
            if ($type == 'input' || $type == 'picker') {
                $field .= $v['params']['tip'] . '_';
            }
        }
        $field = rtrim($field, '_');
        
        $data = [];
        $data['wxapp_id'] = $model::$wxapp_id;
        $data['name'] = $post['page']['params']['name'];
        $data['page'] = json_encode($post);
        $data['format'] = $field;
        $data['time'] = time();
        db('form')->insert($data);
        return $this->renderSuccess('表单添加成功', url('wxapp.page/formlist'));
    }
    
    /**
     * 编辑表单
     * @return mixed
     */
    public function formEdit($id)
    {
        $model = new WxappPageModel;
        
        $data = [];
        $data['id'] = $id;
        $data['wxapp_id'] = $model::$wxapp_id;
        $one = db('form')->where($data)->find();

        if (!$this->request->isAjax()) {
            return $this->fetch('formAdd', [
                'defaultData' => json_encode($model->getFormItems()),
                'jsonData' => $one['page'],
                'opts' => json_encode([
                    'catgory' => CategoryModel::getCacheTree(),
                    'sharingCatgory' => SharingCategoryModel::getCacheTree(),
                    'articleCatgory' => ArticleCategoryModel::getALL(),
                ])
            ]);
        }

        // 接收post数据
        $post = $this->request->post('data', null, null);
        $post = json_decode($post, true);
        $field = '';
        
        foreach ($post['items'] as $v) {
            $type = $v['type'];
            if ($type == 'input' || $type == 'picker') {
                $field .= $v['params']['tip'] . '_';
            }
        }
        $field = rtrim($field, '_');

        $data = [];
        $data['id'] = $id;
        $data['wxapp_id'] = $model::$wxapp_id;
        $data['name'] = $post['page']['params']['name'];
        $data['page'] = json_encode($post);
        $data['format'] = $field;
        $data['time'] = time();
        db('form')->update($data);
        return $this->renderSuccess('表单修改成功', url('wxapp.page/formlist'));
    }

    /**
     * 表单删除
     * @return mixed
     */
    public function formDelete()
    {
        $id = input('id');
        $model = new WxappPageModel;
        $wxapp_id = $model::$wxapp_id;
        $data['id'] = $id;
        $data['wxapp_id'] = $wxapp_id;
        db('form')->where($data)->delete();
        return $this->renderSuccess('删除成功');
    }
    
    /**
     * 表单详情
     * @return mixed
     */
    public function formOne()
    {
        $id = input('id',0,'intval');
        $model = new WxappPageModel;
        $wxapp_id = $model::$wxapp_id;
        $data['id'] = $id;
        $data['wxapp_id'] = $wxapp_id;
        $one = db('form')->where($data)->find(); 
        if($one){
            $field = $one['format'];
            $field = explode('_', $field);
        
            $data = [];
            $data['fid'] = $id;
            $result = db('form_data')->order('id desc')->where($data)->column('content');
            $tmp = [];
            foreach($result as $v){
                $arr = explode(',', $v);
                $tmp[] = $arr;
            }
            return $this->fetch('formOne', [
                'field' => $field,
                'list' => $tmp,
            ]);
        }
    }
}
